<template>
    <el-row class="row1">
        <el-col :span="24">
            <el-row>
                <el-col :span="3">
                    <h1>园区运营</h1>
                </el-col>
                <el-col :span="4">
                    <br>房屋总数量：<el-tag effect="dark" round>{{ houseTotal }}</el-tag>
                </el-col>
                <el-col :span="4">
                    <br>员工总数量：<el-tag type="success" effect="dark" round>{{ employeeTotal }}</el-tag>
                </el-col>
                <el-col :span="4">
                    <br>租户总数量：<el-tag type="warning" effect="dark" round>{{ tenantTotal }}</el-tag>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="1">
                    <el-text>组织</el-text>
                </el-col>
                <el-col :span="5">
                    <el-cascader v-model="selectedOrgId" @focus="openOrgSelect" @change="changeOrgValue"
                        :options="orgList" :props="cascaderProps" placeholder="请选择组织" clearable />
                </el-col>
                <el-col :span="5">
                    <el-text>&nbsp;&nbsp;&nbsp;当前查询数量：</el-text><el-tag type="warning" round>{{ currentHouseTotal
                        }}</el-tag>
                </el-col>
            </el-row><br>
            <el-row>
                <el-col :span="12">
                    <div ref="houseTypeBar" style="width: 100%; height: 300px;"></div>
                </el-col>
                <el-col :span="12">
                    <div ref="houseStatusBar" style="width: 100%; height: 300px;"></div>
                </el-col>

            </el-row>
        </el-col>
    </el-row>

    <el-row class="row2">

        <el-col :span="12">
            <el-row>
                <el-col :span="4">
                    <h1>工单数据</h1>
                </el-col>
                <el-col :span="7">
                    <br><el-text>当前查询数量：</el-text><el-tag round>{{ currentWorkorderTotal }}</el-tag>
                </el-col>
                <el-col :span="7">
                    <br>工单总数量：<el-tag effect="dark" round>{{ workorderTotal }}</el-tag>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">
                    <el-text>时间范围</el-text>
                </el-col>
                <el-col :span="21">
                    <el-date-picker v-model="workorderDateTimeRange" type="datetimerange" start-placeholder="开始"
                        end-placeholder="截至" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" @change="changeWorkorderDateTimeRange" clearable />
                </el-col>
            </el-row><br>
            <el-row>
                <el-col :span="8">
                    <div style="margin-right: 5px;">
                        <el-table :data="workorderNumByCategory" max-height="270" border>
                            <el-table-column prop="name" label="所属工单分类"></el-table-column>
                            <el-table-column prop="value" label="数量" width="60"></el-table-column>
                        </el-table>
                    </div>

                </el-col>
                <el-col :span="16">
                    <div ref="workorderStatusPie" style="width: 100%; height: 300px;"></div>
                </el-col>
            </el-row>
        </el-col>

        <el-col :span="12">
            <el-row>
                <el-col :span="4">
                    <h1>巡查数据</h1>
                </el-col>
                <el-col :span="7">
                    <br><el-text>当前查询数量：</el-text><el-tag type="success" round>{{ currentTaskTotal }}</el-tag>
                </el-col>
                <el-col :span="7">
                    <br>任务总数量：<el-tag type="success" effect="dark" round>{{ taskTotal }}</el-tag>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">
                    <el-text>时间范围</el-text>
                </el-col>
                <el-col :span="21">
                    <el-date-picker v-model="taskDateTimeRange" type="datetimerange" start-placeholder="开始"
                        end-placeholder="截至" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" @change="changeTaskDateTimeRange" clearable />
                </el-col>
            </el-row><br>
            <el-row>
                <el-col :span="10">
                    <div style="margin-right: 5px;">
                        <el-table :data="taskNumByPlan" max-height="270" border>
                            <el-table-column prop="name" label="所属巡查计划"></el-table-column>
                            <el-table-column prop="value" label="数量" width="60"></el-table-column>
                        </el-table>
                    </div>

                </el-col>
                <el-col :span="14">
                    <div ref="taskStatusPie" style="width: 100%; height: 300px;"></div>
                </el-col>
            </el-row>
        </el-col>

    </el-row>

</template>

<script setup>
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
const router = useRouter();
import { orgGetService } from '@/api/property.js'
import { totalGetService, houseStatGetService, taskStatGetService, workorderStatGetService } from '@/api/other.js'

const houseTypeBar = ref(null);
const houseStatusBar = ref(null);
const taskStatusPie = ref(null);
const workorderStatusPie = ref(null);

// 绘制房屋类型柱状图
function drawHouseTypeBar() {
    if (houseTypeBar.value) {
        const chartInstance = echarts.init(houseTypeBar.value);

        const option = {
            title: {
                text: '房屋类型'
            },
            tooltip: {
                // trigger: 'item',
                // formatter: '{b} : {c} 间 '
                // 内容为空时应用默认样式
            },
            legend: {
                // 内容为空时应用默认样式
            },
            xAxis: {
                type: 'category',
                data: typeNameList.value,
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: '',
                data: typeValueList.value,
                type: 'bar',
                barWidth: '40%', // 设置柱子宽度为图表宽度的10%。也可以直接指定一个具体的像素值，如'10'
                itemStyle: {
                    color: '#409EFF',
                }
            }]
        };

        chartInstance.setOption(option);
    }
}
// 绘制房屋状态柱状图
function drawHouseStatusBar() {
    if (houseStatusBar.value) {
        const chartInstance = echarts.init(houseStatusBar.value);

        const option = {
            title: {
                text: '房屋状态'
            },
            tooltip: {
                // trigger: 'item',
                // formatter: '{b} : {c} 间 '
                // 内容为空时应用默认样式
            },
            legend: {
                // 内容为空时应用默认样式
            },
            xAxis: {
                type: 'category',
                data: statusNameList.value,
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: '',
                data: statusValueList.value,
                type: 'bar',
                barWidth: '40%', // 设置柱子宽度为图表宽度的10%。也可以直接指定一个具体的像素值，如'10'
                itemStyle: {
                    color: '#67C23A',
                }
            }]
        };

        chartInstance.setOption(option);
    }
}
// 绘制任务状态饼图
const drawTaskStatusPie = () => {
    if (taskStatusPie.value) {
        const chartInstance = echarts.init(taskStatusPie.value);
        let options = {
            title: {
                text: ''
            },
            tooltip: {},
            legend: {
                data: ['已完成', '未完成', '已关闭']
            },
            series: [{
                name: '',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                    { value: taskCompleteNum.value, name: '已完成', itemStyle: { color: '#91CC75' } },
                    { value: taskUncompleteNum.value, name: '未完成', itemStyle: { color: '#FAC858' } },
                    { value: taskCloseNum.value, name: '已关闭', itemStyle: { color: '#9093B3' } }
                ],
                emphasis: {
                    show: true,
                    textStyle: {
                        fontSize: '30',
                        fontWeight: 'bold',
                    },
                },
            }]
        };

        chartInstance.setOption(options)
    }
}
// 绘制工单状态饼图
const drawWorkorderStatusPie = () => {
    if (workorderStatusPie.value) {
        const chartInstance = echarts.init(workorderStatusPie.value);
        let options = {
            title: {
                text: ''    // 整体图例的标题
            },
            tooltip: {},
            legend: {
                data: ['已完成', '处理中', '待接收', '已关闭']
            },
            series: [{
                name: '',   // 鼠标悬浮时显示的数据标题
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                    { value: workorderCompleteNum.value, name: '已完成', itemStyle: { color: '#91CC75' } },
                    { value: workorderUncompleteNum.value, name: '处理中', itemStyle: { color: '#FAC858' } },
                    { value: workorderUnreceiveNum.value, name: '待接收', itemStyle: { color: '#5470C6' } },
                    { value: workorderCloseNum.value, name: '已关闭', itemStyle: { color: '#9093B3' } }
                ],
                emphasis: {
                    show: true,
                    textStyle: {
                        fontSize: '30',
                        fontWeight: 'bold',
                    },
                },
            }]
        };

        chartInstance.setOption(options)
    }

}
onMounted(() => {
    onPageOpen();   // 由于echarts的特性，图标的初始化需要放在onMounted里
});

const cascaderProps = { // 级联选择框参数
    expandTrigger: 'hover',// as const,
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'name',
}

let isRequestedOrgList = false  // 是否请求过org列表
const orgList = ref()   // org列表
const selectedOrgId = ref()  // 选中的org

const houseTotal = ref(0)   // 房屋总数
const employeeTotal = ref(0)    // 员工总数
const tenantTotal = ref(0)  // 租户总数
const workorderTotal = ref(0)  // 工单总数
const taskTotal = ref(0)  // 任务总数
const currentHouseTotal = ref() // 当前条件下的房屋总数
const currentWorkorderTotal = ref() // 当前条件下的工单总数
const currentTaskTotal = ref()  // 当前条件下的任务总数

const typeNameList = ref([]);   // 房屋类型名称列表
const typeValueList = ref([]);  // 房屋类型数量列表
const statusNameList = ref([]); // 房屋状态名称列表
const statusValueList = ref([]);    // 房屋状态数量列表

const taskNumByPlan = ref([])   // 计划下的任务数量列表
const workorderNumByCategory = ref([])  // 类型下的工单数量列表

const taskCompleteNum = ref(0)  // 已完成任务数量
const taskUncompleteNum = ref(0)    // 未完成任务数量
const taskCloseNum = ref(0) // 已关闭任务数量
const workorderUnreceiveNum = ref(0) // 未接收工单数量
const workorderCompleteNum = ref(0) // 已完成工单数量
const workorderUncompleteNum = ref(0)   // 未完成工单数量
const workorderCloseNum = ref(0)    // 已关闭工单数量

const taskDateTimeRange = ref() // 任务时间范围
const workorderDateTimeRange = ref() // 工单时间范围

// 打开页面时对需要的数据初始化
function onPageOpen() {
    getTotal();
    changeOrgValue();
    changeWorkorderDateTimeRange();
    changeTaskDateTimeRange();
}
// 获取三个总数（房屋、员工、租户）
async function getTotal() {
    try {
        let result = await totalGetService();
        if (result.code == 200) {
            houseTotal.value = result.data.houseTotal
            employeeTotal.value = result.data.employeeTotal
            tenantTotal.value = result.data.tenantTotal
            workorderTotal.value = result.data.workorderTotal
            taskTotal.value = result.data.taskTotal
        } else if (result.code == 401) {
            router.push('/login')
            ElMessage.error(result.msg)
        } else {
            ElMessage.warning(result.msg)
        }
    } catch {
        ElMessage.error("系统异常 （getTotal）")
    }
}
// 选择org
async function openOrgSelect() {
    // 如果是第一次选择org，则需请求一次orgList数据
    if (!isRequestedOrgList) {
        try {
            let result = await orgGetService(null, 0, 0);
            if (result.code == 200) {
                orgList.value = result.data.list
                isRequestedOrgList = true
            } else if (result.code == 401) {
                router.push('/login')
                ElMessage.error(result.msg)
            } else {
                ElMessage.warning(result.msg)
            }
        } catch {
            ElMessage.error("系统异常 （getOrgList）")
        }
    }
}
// 选择org后，请求房屋统计数据
async function changeOrgValue() {
    try {
        if (selectedOrgId.value == null) {
            selectedOrgId.value = 0
        }
        let result = await houseStatGetService(selectedOrgId.value);
        if (result.code == 200) {
            typeNameList.value = result.data.typeName
            typeValueList.value = result.data.typeValue
            statusNameList.value = result.data.statusName
            statusValueList.value = result.data.statusValue
            currentHouseTotal.value = result.data.houseTotal
            drawHouseTypeBar();
            drawHouseStatusBar();
        } else if (result.code == 401) {
            router.push('/login')
            ElMessage.error(result.msg)
        } else {
            ElMessage.warning(result.msg)
        }
    } catch {
        ElMessage.error("系统异常 （getHouseStat）")
    }
}
// 更改了taskDateTimeRange
async function changeTaskDateTimeRange() {
    try {
        let result = null;
        if (taskDateTimeRange.value == null) {
            result = await taskStatGetService(["0001-01-01T00:00", "9999-12-31T15:59:59"]);
        } else {
            result = await taskStatGetService(taskDateTimeRange.value);
        }
        if (result.code == 200) {
            currentTaskTotal.value = result.data.taskTotal
            taskUncompleteNum.value = result.data.statusValue[0]
            taskCompleteNum.value = result.data.statusValue[1]
            taskCloseNum.value = result.data.statusValue[2]
            taskNumByPlan.value = result.data.planStat
            drawTaskStatusPie();
        } else if (result.code == 401) {
            router.push('/login')
            ElMessage.error(result.msg)
        } else {
            ElMessage.warning(result.msg)
        }
    } catch {
        ElMessage.error("系统异常 (GetTaskStat)")
    }
}
// 更改了workorderDateTimeRange
async function changeWorkorderDateTimeRange() {
    try {
        let result = null;
        if (workorderDateTimeRange.value == null) {
            result = await workorderStatGetService(["0001-01-01T00:00", "9999-12-31T15:59:59"]);
        } else {
            result = await workorderStatGetService(workorderDateTimeRange.value);
        }
        if (result.code == 200) {
            currentWorkorderTotal.value = result.data.workorderTotal
            workorderUnreceiveNum.value = result.data.statusValue[0]
            workorderUncompleteNum.value = result.data.statusValue[1]
            workorderCompleteNum.value = result.data.statusValue[2]
            workorderCloseNum.value = result.data.statusValue[3]
            workorderNumByCategory.value = result.data.categoryStat
            drawWorkorderStatusPie();
        } else if (result.code == 401) {
            router.push('/login')
            ElMessage.error(result.msg)
        } else {
            ElMessage.warning(result.msg)
        }
    } catch {
        ElMessage.error("系统异常 (GetWorkorderStat)")
    }
}

</script>

<style scoped></style>